package com.movitech.mobile.cz.base.purchase.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.movitech.mobile.cz.base.bizconfig.service.SStrategicCategoryService;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.PageCode;
import com.movitech.mobile.cz.base.common.util.StringUtils;
import com.movitech.mobile.cz.base.purchase.entity.PStrategicPurchaseRequired;
import com.movitech.mobile.cz.base.purchase.entity.ext.*;
import com.movitech.mobile.cz.base.purchase.mapper.PStrategicPurchaseRequiredMapper;
import com.movitech.mobile.cz.base.purchase.service.PSpRequiredDetailService;
import com.movitech.mobile.cz.base.purchase.service.PStrategicPurchaseRequiredService;
import com.movitech.mobile.cz.base.sys.entity.SRegionalCompany;
import com.movitech.mobile.cz.base.sys.service.SRegionalCompanyService;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 战略采购需求 服务实现类
 * </p>
 *
 * @author Movitech Mobile
 * @since 2018-03-15
 */
@Service
public class PStrategicPurchaseRequiredServiceImpl extends ServiceImpl<PStrategicPurchaseRequiredMapper, PStrategicPurchaseRequired> implements PStrategicPurchaseRequiredService {

    @Autowired
    private PStrategicPurchaseRequiredMapper pStrategicPurchaseRequiredMapper;
    @Autowired
    private PSpRequiredDetailService pSpRequiredDetailService;
    @Autowired
    private SStrategicCategoryService sStrategicCategoryService;
    @Autowired
    private SRegionalCompanyService sRegionalCompanyService;

    @Override
    public PageCode findStrategicPurchaseRequiredList(StrategicPurchaseRequiredFindRequest strategicPurchaseRequiredFindRequest) {
        PageCode pageCode = new PageCode(strategicPurchaseRequiredFindRequest.getPageNumber(), strategicPurchaseRequiredFindRequest.getPageSize());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
        map.put("pageSize", pageCode.getPageSize());

        map.put("purchaseYear", strategicPurchaseRequiredFindRequest.getPlanYear());
        map.put("regionalCompanyId", strategicPurchaseRequiredFindRequest.getRegionalCompanyId());
        map.put("projectId", strategicPurchaseRequiredFindRequest.getProjectId());

        Integer count = pStrategicPurchaseRequiredMapper.findStrategicPurchaseRequiredListCount(map);
        pageCode.setCount(count == null ? 0 : count);
        Map<String,String> categoryServiceIdAndNames = sStrategicCategoryService.findIdAndNames();
        List<PStrategicPurchaseRequired> ls = pStrategicPurchaseRequiredMapper.findStrategicPurchaseRequiredList(map);
        for(PStrategicPurchaseRequired p:ls){
            String ca = "";
            if(p.getCategoryIds()!=null){
                String[] cc = p.getCategoryIds().trim().split(",");
                for(String c:cc){
                    if(categoryServiceIdAndNames.get(c)!=null){
                        ca+=","+categoryServiceIdAndNames.get(c);
                    }
                }
            }
            if(ca.startsWith(","))
                ca = ca.substring(1);
            p.setCategoryIds(ca);
        }
        pageCode.setList(ls);
        return pageCode;
    }

    @Override
    public ExtPStrategicPurchaseRequired getById(String id) {
        ExtPStrategicPurchaseRequired extPStrategicPurchaseRequired = pStrategicPurchaseRequiredMapper.getById(id);
        SpRequiredDetailFindRequest requiredDetailFindRequest = new SpRequiredDetailFindRequest();
        requiredDetailFindRequest.setStrategicPurchaseRequiredId(id);
        List<ExtPSpRequiredDetail> pSpRequiredDetailList = pSpRequiredDetailService.findRequiredDetail(requiredDetailFindRequest);
        if(extPStrategicPurchaseRequired == null){
            extPStrategicPurchaseRequired = new ExtPStrategicPurchaseRequired();
            extPStrategicPurchaseRequired.setRegionalCompanyName(UserUtils.getCurrentUser().getRegionalCompanyName());
            extPStrategicPurchaseRequired.setRegionalCompanyId(UserUtils.getCurrentUser().getRegionalCompanyId());
        }
        extPStrategicPurchaseRequired.setRequiredDetailList(pSpRequiredDetailList);
        return extPStrategicPurchaseRequired;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public boolean savePStrategicPurchaseRequired(PStrategicPurchaseRequiredSaveRequest strategicPurchaseRequiredSaveRequest) {
        try {
            PStrategicPurchaseRequired strategicPurchaseRequired = strategicPurchaseRequiredSaveRequest.getStrategicPurchaseRequired();
            if(StringUtils.isNotEmpty(strategicPurchaseRequired.getId()))
                pSpRequiredDetailService.deleteByRequireId(strategicPurchaseRequired.getId());
            else{
                strategicPurchaseRequired.setBaseFeilds(UserUtils.getCurrentUserId(),"",CommonConstants.DEL_FLAG_NORMAL,true);
            }
            Integer belongGroupRequired = 0;
            Integer belongRegionalCmpyRequired = 0;
            StringBuffer categoryIds = new StringBuffer();
            //没有详情
            if (strategicPurchaseRequiredSaveRequest.getExtPSpRequiredDetails() == null || strategicPurchaseRequiredSaveRequest.getExtPSpRequiredDetails().size() == 0) {
            } else {//存在详情
                int index = 0;

                for (ExtPSpRequiredDetail extPSpRequiredDetail : strategicPurchaseRequiredSaveRequest.getExtPSpRequiredDetails()) {
                    SRegionalCompany sRegionalCompany = sRegionalCompanyService.selectById(extPSpRequiredDetail.getRequiredAttributionId());

                    if(sRegionalCompany!=null){
                        if(sRegionalCompany.getRcType()==1)belongGroupRequired++;
                        else belongRegionalCmpyRequired++;
                    }

                    extPSpRequiredDetail.setId(null);
                    extPSpRequiredDetail.setBaseFeilds(UserUtils.getCurrentUserId(),"", CommonConstants.DEL_FLAG_NORMAL,true);
                    extPSpRequiredDetail.setStrategicPurchaseRequiredId(strategicPurchaseRequired.getId());
                    if (index == 0) {
                        categoryIds.append((extPSpRequiredDetail.getRequiredCategoryId() == null ? "" : extPSpRequiredDetail.getRequiredCategoryId()));
                    } else {
                        categoryIds.append("," + (extPSpRequiredDetail.getRequiredCategoryId() == null ? "" : extPSpRequiredDetail.getRequiredCategoryId()));
                    }
                    pSpRequiredDetailService.insert(extPSpRequiredDetail);
                    index++;
                }
            }
            strategicPurchaseRequired.setCategoryIds(categoryIds.toString());
            strategicPurchaseRequired.setBelongGroupRequired(belongGroupRequired);
            strategicPurchaseRequired.setBelongRegionalCmpyRequired(belongRegionalCmpyRequired);
            insertOrUpdate(strategicPurchaseRequired);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(),e.getCause());
        }
        return false;
    }
}
